package cn.sx10.controller;

import javax.json.Json;
import javax.json.JsonString;
import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

import cn.sx10.model.Grade;
import cn.sx10.model.Student;
import cn.sx10.service.GradeService;
import cn.sx10.service.StudentService;
import cn.sx10.service.impl.GradeServiceImpl;
import cn.sx10.service.impl.StudentServiceImpl;
import com.alibaba.fastjson.JSON;


@WebServlet("/student.do")
public class studentController extends HttpServlet {
    StudentService studentService = new StudentServiceImpl();
    GradeService gradeService = new GradeServiceImpl();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset:UTF-8");
        String option= request.getParameter("action");

        switch (option){
            case "list":   //查看所有学员信息
                list(request,response);
                break;
            case "demand":      //查看学员详细信息
                demand(request,response);
                break;
            case "showadd":   //新增学员页面
                showadd(request,response);
                break;
            case "add":         //新增学员
                try {
                    add(request,response);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                break;
            case "backfill":         //新增失败数据回填
                backfill(request,response);
                break;
            case "delete":      //删除学员
                delete(request,response);
                break;
            case "modifyview":  //显示修改页面
                modifyview(request,response);
                break;
            case "modify":      //修改学员信息
                try {
                    modify(request,response);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                break;
            case "queryNum":       //判断学员学号是否重复
                queryNum(request,response);
                break;
            case "search":       //判断学员学号是否重复
                search(request,response);
                break;
        }

    }


//    用户搜索方法
    private void search(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String studentNo = request.getParameter("studentNo");
        String studentName =request.getParameter("studentName");

        Student student = new Student();
        if(studentNo!=""){
            student.setStudentNo(Integer.parseInt(studentNo));
            System.out.println(studentNo);
        }
        if (studentName!=null||studentName!=""){
            student.setStudentName(studentName);
            System.out.println(studentName);
        }

        List<Student> students = studentService.search(student);

        String jsonString = JSON.toJSONString(students);
        PrintWriter printWriter = response.getWriter();
        printWriter.print(jsonString);
        printWriter.flush();
        printWriter.close();

    }

    private void queryNum(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String studentNo = request.getParameter("studentNo");
        System.out.println(studentNo);
        //判断学号是否重复
        boolean isOk = studentService.queryNum(studentNo);
        //拼接Json数据（以后用工具）
        String jsonString ="{\"result\":\""+isOk+"\"}" ;
        PrintWriter writer = response.getWriter();
        writer.print(jsonString);
        //关闭数据写操作
        writer.flush();
        writer.close();
    }

    private void modify(HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException, ServletException {
        Student student = new Student();
        student.setStudentNo(Long.parseLong(request.getParameter("studentNo")));
        student.setStudentName(request.getParameter("studentName"));
        student.setLoginPwd(request.getParameter("loginPwd"));
        student.setSex(request.getParameter("sex"));
        student.setGradeId(Long.parseLong(request.getParameter("gradeId")));
        student.setPhone(request.getParameter("phone"));
        student.setAddress(request.getParameter("address"));
        String date= request.getParameter("BornDate");
        if (date==""){
            student.setBornDate(null);
        }
        else{
            student.setBornDate(format.parse(date));
        }
        student.setEmail(request.getParameter("email"));
        student.setIdentityCard(request.getParameter("IdentityCard"));

        boolean isOK = studentService.modify(student);
        if (isOK){
            response.sendRedirect("student.do?action=list");
        }
        else{
            request.setAttribute("student",student);
            request.getRequestDispatcher("student.do?action=backfill").forward(request,response);
        }
    }

    private void modifyview(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String studentno = request.getParameter("studentno");
        Student student =studentService.modifyview(studentno);
        //将学员信息封装
        request.setAttribute("student",student);
        //将viewtype赋予修改信息
        request.setAttribute("viewtype","modify");
        //将年级信息封装发送，获取年级信息
        List<Grade> grades =gradeService.show();
        request.setAttribute("grades",grades);
        request.getRequestDispatcher("WEB-INF/view/studentadd.jsp?viewtype=modify").forward(request,response);
    }

    //显示学员详情
    private void demand(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int studentno = Integer.parseInt(request.getParameter("studentno"));
        List<Student> studentDemand = studentService.singleDemand(studentno);
        request.setAttribute("studentDemand",studentDemand);

        request.getRequestDispatcher("WEB-INF/view/details.jsp").forward(request,response);
    }

//删除学员
    private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int studentno = Integer.parseInt(request.getParameter("studentno"));
        int studentdel = studentService.delete(studentno);
        list(request,response);
    }

    //显示新增页面
    private void showadd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Grade> grades =gradeService.show();
        request.setAttribute("grades",grades);
        request.getRequestDispatcher("WEB-INF/view/studentadd.jsp").forward(request,response);
    }

    //新增学员
    private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {

        Student student = new Student();
        student.setStudentNo(Long.parseLong(request.getParameter("studentNo")));
        student.setStudentName(request.getParameter("studentName"));
        student.setLoginPwd(request.getParameter("loginPwd"));
        student.setSex(request.getParameter("sex"));
        student.setGradeId(Long.parseLong(request.getParameter("gradeId")));
        student.setPhone(request.getParameter("phone"));
        student.setAddress(request.getParameter("address"));
        String date= request.getParameter("BornDate");
        if (date==""){
            student.setBornDate(null);
        }
        else{
            student.setBornDate(format.parse(date));
        }

        student.setEmail(request.getParameter("email"));
        student.setIdentityCard(request.getParameter("IdentityCard"));

        boolean isOK = studentService.findAdd(student);
        if (isOK){
            response.sendRedirect("student.do?action=list");
        }
        else{
            request.setAttribute("student",student);
            request.getRequestDispatcher("student.do?action=backfill").forward(request,response);
        }
    }

    //数据回填方法
    private void backfill(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Grade> grades = gradeService.show();
        request.setAttribute("grades",grades);
        request.getRequestDispatcher("WEB-INF/view/studentadd.jsp").forward(request,response);
    }


    //显示所有学员信息
    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Student> students = studentService.findAll();
        request.setAttribute("students",students);
        request.getRequestDispatcher("WEB-INF/view/studentlist.jsp").forward(request,response);
    }
}

